//
//  UserEditViewController.m
//  WindRunner
//
//  Created by leeqb on 11/24/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "UserEditViewController.h"
#import "AFURLConnectionOperation.h"
#import "AFURLSessionManager.h"
#import "AFHTTPRequestOperationManager.h"

typedef enum {
    PopSelectTypeActivity
} PopSelectType;

@interface UserEditViewController ()
{
    UIView *_blackAlphaView;
    NSData  *_selectedImageData;
    
    NSInteger _currPopType;
    NSArray *_currSelectionItems;
    NSArray *_activityTypeItems;
    NSArray *_feelingItems;
    NSArray *_statureItems;
    NSArray *_hobbyItems;
    
    NSInteger _currButtonTag;
    NSInteger _currPopSelectIndex;
    NSInteger _currActivityIndex;
    NSInteger _currFeelingIndex;
    NSInteger _currBodyIndex;
    NSInteger _currHobbyIndex;
}
@end

@implementation UserEditViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        _currPopSelectIndex = -1;
        
        _blackAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _blackAlphaView.backgroundColor = [UIColor blackColor];
        _blackAlphaView.alpha = 0.5f;
        
        _activityTypeItems = @[LocalStringSetting(@"UE_ACTIVITY_TYPE1"), LocalStringSetting(@"UE_ACTIVITY_TYPE2"), LocalStringSetting(@"UE_ACTIVITY_TYPE3"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE4"), LocalStringSetting(@"UE_ACTIVITY_TYPE5"), LocalStringSetting(@"UE_ACTIVITY_TYPE6"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE7"), LocalStringSetting(@"UE_ACTIVITY_TYPE8"), LocalStringSetting(@"UE_ACTIVITY_TYPE9"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE10"), LocalStringSetting(@"UE_ACTIVITY_TYPE11"), LocalStringSetting(@"UE_ACTIVITY_TYPE12"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE13"), LocalStringSetting(@"UE_ACTIVITY_TYPE14"), LocalStringSetting(@"UE_ACTIVITY_TYPE15"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE16"), LocalStringSetting(@"UE_ACTIVITY_TYPE17"), LocalStringSetting(@"UE_ACTIVITY_TYPE18"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE19"), LocalStringSetting(@"UE_ACTIVITY_TYPE20"), LocalStringSetting(@"UE_ACTIVITY_TYPE21"),
                               LocalStringSetting(@"UE_ACTIVITY_TYPE22"), LocalStringSetting(@"UE_ACTIVITY_TYPE23"), LocalStringSetting(@"UE_ACTIVITY_TYPE24")];
        _feelingItems = @[LocalStringSetting(@"UE_FEELING1"), LocalStringSetting(@"UE_FEELING2"), LocalStringSetting(@"UE_FEELING3")];
        _statureItems = @[LocalStringSetting(@"UE_STATURE1"), LocalStringSetting(@"UE_STATURE2"), LocalStringSetting(@"UE_STATURE3")];
        _hobbyItems = @[LocalStringSetting(@"UE_HOBBY1"), LocalStringSetting(@"UE_HOBBY2"), LocalStringSetting(@"UE_HOBBY3")];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = LocalStringSetting(@"NAV_TITLE_USER_EDIT");
    _basicLabel.text = LocalStringSetting(@"UE_BASIC_LABEL");
    _idLabel.text = [NSString stringWithFormat:@"%@%@", LocalStringSetting(@"UE_ID_LABEL"), [AuthHelper getCurrentUser][@"id"]];
    _nickNameLabel.text = LocalStringSetting(@"UE_NICK_LABEL");
    _nickInput.placeholder = LocalStringSetting(@"UE_NICK_PLH");
    _activityTypeLabel.text = LocalStringSetting(@"UE_ACTIVITY_LABEL");
    _activityInput.placeholder = LocalStringSetting(@"UE_ACTIVITY_PLH");
    _feelingLabel.text = LocalStringSetting(@"UE_FEELING_LABEL");
    _feelingInput.placeholder = LocalStringSetting(@"UE_FEELING_PLH");
    _heightLabel.text = LocalStringSetting(@"UE_HEIGHT_LABEL");
    _heightInput.placeholder = LocalStringSetting(@"UE_HEIGHT_PLH");
    _weightLabel.text = LocalStringSetting(@"UE_WEIGHT_LABEL");
    _weightInput.placeholder = LocalStringSetting(@"UE_WEIGHT_PLH");
    _bodyLabel.text = LocalStringSetting(@"UE_BODY_LABEL");
    _bodyInput.placeholder = LocalStringSetting(@"UE_BODY_PLH");
    _hobbyLabel.text = LocalStringSetting(@"UE_HOBBY_LABEL");
    _hobbyInput.placeholder = LocalStringSetting(@"UE_HOBBY_PLH");
    _birthLabel.text = LocalStringSetting(@"UE_BIRTH_LABEL");
    _birthInput.placeholder = LocalStringSetting(@"UE_BIRTH_PLH");
    
    _pickImageButton.layer.cornerRadius = CGRectGetHeight(_pickImageButton.bounds) / 2;
    _pickImageButton.layer.masksToBounds = YES;
    
    NSString *imgurl = [NSString formatString:self.data[@"headicon"]];
    LEDownloadManager *downloadManager = [[LEDownloadManager alloc] init];
    downloadManager.delegate = self;
    [downloadManager downLoadImageWithURL:imgurl imagetype:@"UserEditImages"];
    
    if(![[NSString formatString:self.data[@"activetype"]] isEqualToString:@""]) {
        _currActivityIndex = [[NSString formatString:self.data[@"activetype"]] integerValue];
    } else {
        _currActivityIndex = -1;
    }
    
    if(![[NSString formatString:self.data[@"emotion"]] isEqualToString:@""]) {
        _currFeelingIndex = [[NSString formatString:self.data[@"emotion"]] integerValue];
    } else {
        _currFeelingIndex = -1;
    }
    
    if(![[NSString formatString:self.data[@"body"]] isEqualToString:@""]) {
        _currBodyIndex = [[NSString formatString:self.data[@"body"]] integerValue];
    } else {
        _currBodyIndex = -1;
    }
    
    if(![[NSString formatString:self.data[@"interests"]] isEqualToString:@""]) {
        _currHobbyIndex = [[NSString formatString:self.data[@"interests"]] integerValue];
    } else {
        _currHobbyIndex = -1;
    }
    
    _nickInput.text = [NSString formatString:self.data[@"nickname"]];
    _heightInput.text = [NSString formatString:self.data[@"height"]];
    _weightInput.text = [NSString formatString:self.data[@"weight"]];
    
    @try {
        _activityInput.text = _activityTypeItems[_currActivityIndex];
    }
    @catch (NSException *exception) {
    }
    @finally {
    }
    
    @try {
        _feelingInput.text = _feelingItems[_currFeelingIndex];
    }
    @catch (NSException *exception) {
    }
    @finally {
    }
    
    @try {
        _bodyInput.text = _statureItems[_currBodyIndex];
    }
    @catch (NSException *exception) {
    }
    @finally {
    }
    
    @try {
        _hobbyInput.text = _hobbyItems[_currHobbyIndex];
    }
    @catch (NSException *exception) {
    }
    @finally {
    }
    
    NSString *birthDateStr = [NSString formatString:self.data[@"birthday"]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy/MM/dd";
    if(![birthDateStr isEqualToString:@""]) {
        NSDate *birthDate = [NSDate dateWithTimeIntervalSince1970:[birthDateStr doubleValue]/1000];
        _birthInput.text = [dateFormatter stringFromDate:birthDate];
    } else {
        _birthInput.text = [dateFormatter stringFromDate:[NSDate date]];
    }
}

// 点击回车隐藏键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)selectImage:(id)sender {
    PickImageView *pickView = [[PickImageView alloc] init];
    pickView.delegate = self;
    [pickView show];
}

- (IBAction)saveInfo:(UIButton *)sender {
    NSString *imgurl = [NSString formatString:self.data[@"headicon"]];
    NSString *nick = [NSString formatString:_nickInput.text];
    NSString *height = [NSString formatString:_heightInput.text];
    NSString *weight = [NSString formatString:_weightInput.text];
    NSString *birth = [NSString formatString:_birthInput.text];
    
    if(!_selectedImageData && [imgurl isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_IMAGE")];
        return;
    }
    
    if([nick isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_NICK")];
        return;
    }
    
    if(_currActivityIndex == -1) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_ACTIVITY")];
        return;
    }
    
    if(_currFeelingIndex == -1) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_FEELING")];
        return;
    }
    
    if([height isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_HEIGHT")];
        return;
    }
    
    if([weight isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_WEIGHT")];
        return;
    }
    
    if(_currBodyIndex == -1) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_BODY")];
        return;
    }
    
    if(_currHobbyIndex == -1) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_HOBBY")];
        return;
    }
    
    if([birth isEqualToString:@""]) {
        [FMToast showMessage:LocalStringSetting(@"UE_TIP_NO_BIRTH")];
        return;
    }
    
    NSTimeInterval birthTimestamp = [_popDatePicker.date timeIntervalSince1970] * 1000;
    NSDictionary *requestData = @{@"username":[AuthHelper getCurrentUser][@"account"],
                                  @"pwd":[AuthHelper getCurrentUser][@"pwd"],
                                  @"nickname":nick,
                                  @"activetype":[NSString stringWithFormat:@"%@", @(_currActivityIndex)],
                                  @"emotion":[NSString stringWithFormat:@"%@", @(_currFeelingIndex)],
                                  @"height":height,
                                  @"weight":weight,
                                  @"body":[NSString stringWithFormat:@"%@", @(_currBodyIndex)],
                                  @"interests":[NSString stringWithFormat:@"%@", @(_currHobbyIndex)],
                                  @"birthday":[NSString stringWithFormat:@"%lld", (long long)birthTimestamp]};
    
    NSString *urlString = [NSString stringWithFormat:@"%@useredit", BASE_API_URL_WINDRUNNER];
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];;
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:requestData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(_selectedImageData) {
            [formData appendPartWithFileData:_selectedImageData name:@"headicon" fileName:@"ActivityImage.png" mimeType:@"image/png"];
        }
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSProgress *progress = nil;
    
    [FMToast showLoading:LocalStringCommon(@"OPER_DOING")];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if(!error) {
            [FMToast showMessage:LocalStringCommon(@"OPER_SUCC")];
            
            NSError *err;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&err];
            
            NSDictionary *record = result[@"record"];
            if(record && ![record isEqual:[NSNull null]]) {
                NSMutableDictionary *temp = [NSMutableDictionary dictionary];
                for(NSString *key in record.allKeys) {
                    if([record[key] isEqual:[NSNull null]]) {
                        [temp setValue:@"" forKey:key];
                    } else {
                        [temp setValue:record[key] forKey:key];
                    }
                }
                
                [AuthHelper setCurrentUser:temp];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            [FMToast showMessage:LocalStringCommon(@"OPER_FAIL")];
        }
    }];
    
    [uploadTask resume];
}

- (IBAction)popViewOK:(UIButton *)sender {
    if(_currPopType == 1) {
        if(_currButtonTag == 1) {
            _currActivityIndex = _currPopSelectIndex;
            _activityInput.text = _activityTypeItems[_currPopSelectIndex];
        } else if(_currButtonTag == 2) {
            _currFeelingIndex = _currPopSelectIndex;
            _feelingInput.text = _feelingItems[_currPopSelectIndex];
        } else if(_currButtonTag == 3) {
            _currBodyIndex = _currPopSelectIndex;
            _bodyInput.text = _statureItems[_currPopSelectIndex];
        } else if(_currButtonTag == 4) {
            _currHobbyIndex = _currPopSelectIndex;
            _hobbyInput.text = _hobbyItems[_currPopSelectIndex];
        }
        
        [_popSelectView removeFromSuperview];
    } else if(_currPopType == 2) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateStyle = kCFDateFormatterShortStyle;
        _birthInput.text = [dateFormatter stringFromDate:_popDatePicker.date];
        [_popDateSelectView removeFromSuperview];
    }
    [_blackAlphaView removeFromSuperview];
}

- (IBAction)showPopSelectView:(UIButton *)sender {
    _currPopType = 1;
    _currPopSelectIndex = 0;
    _currButtonTag = sender.tag;
    
    if(sender.tag == 1) {
        _currSelectionItems = _activityTypeItems;
        [_popPickerView selectRow:_currActivityIndex inComponent:0 animated:YES];
    } else if(sender.tag == 2) {
        _currSelectionItems = _feelingItems;
        [_popPickerView selectRow:_currFeelingIndex inComponent:0 animated:YES];
    } else if(sender.tag == 3) {
        _currSelectionItems = _statureItems;
        [_popPickerView selectRow:_currBodyIndex inComponent:0 animated:YES];
    } else if(sender.tag == 4) {
        _currSelectionItems = _hobbyItems;
        [_popPickerView selectRow:_currHobbyIndex inComponent:0 animated:YES];
    }
    [_popPickerView reloadComponent:0];
    [_popPickerView selectRow:0 inComponent:0 animated:NO];
    
    CGRect rect = _popSelectView.frame;
    rect.origin.x = (SCREEN_WIDTH - rect.size.width) / 2;
    rect.origin.y = (SCREEN_HEIGHT - rect.size.height) / 2;
    _popSelectView.frame = rect;
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:_blackAlphaView];
    [keyWindow addSubview:_popSelectView];
}

- (IBAction)showPopDateSelectView:(UIButton *)sender {
    _currPopType = 2;
    
    CGRect rect = _popDateSelectView.frame;
    rect.origin.x = (SCREEN_WIDTH - rect.size.width) / 2;
    rect.origin.y = (SCREEN_HEIGHT - rect.size.height) / 2;
    _popDateSelectView.frame = rect;
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:_blackAlphaView];
    [keyWindow addSubview:_popDateSelectView];
}

- (void)imageTypeSelected:(UIImagePickerController *)vc
{
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:^{
    }];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _currSelectionItems.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return _currSelectionItems[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _currPopSelectIndex = row;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    _selectedImageData = UIImagePNGRepresentation(editedImage);
    editedImage = [UIImage imageWithData:_selectedImageData];
    [self.pickImageButton setBackgroundImage:editedImage forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

// 头像图片下载
- (void)downloadImage:(LEDownloadManager *)loadImage downloadFinished:(UIImage *)image
{
    [_pickImageButton setBackgroundImage:image forState:UIControlStateNormal];
}

@end
